package controller;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
// 导入所需的类
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Map;
import java.util.HashMap;

@WebServlet(urlPatterns="/LoginServlet", loadOnStartup=1)
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    // 存储学生信息，键为姓名，值为学号
    private Map<String, String> studentMap = new HashMap<>();

    // 系统启动时间
    private long systemStartTime;

    @Override
    public void init() throws ServletException {
        super.init();
        // 读取 students.csv 文件
        String filePath = "C:\\Users\\angel\\Documents\\javaWeb\\studentLogin\\src\\main\\webapp\\WEB-INF\\classes\\students.csv";

        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("students.csv 文件不存在！");
            return;
        }

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            // 按行读取文件内容
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length >= 2) {
                    String name = parts[0].trim();
                    String studentId = parts[1].trim();
                    // 将姓名和学号存入 Map
                    studentMap.put(name, studentId);
                }
            }
            System.out.println("学生信息读取完毕，共 " + studentMap.size() + " 条记录。");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 记录系统启动时间
        systemStartTime = System.currentTimeMillis();
        // 将系统启动时间存入 ServletContext，供 JSP 页面获取
        getServletContext().setAttribute("systemStartTime", systemStartTime);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置请求和响应的编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 检查系统是否超过5分钟
        Long systemStartTime = (Long) getServletContext().getAttribute("systemStartTime");
        if (systemStartTime == null) {
            response.sendRedirect("outtime.jsp");
            return;
        }
        long currentTime = System.currentTimeMillis();
        if (currentTime - systemStartTime > 5 * 60 * 1000) {
            // 超过5分钟，重定向到 outtime.jsp
            response.sendRedirect("outtime.jsp");
            return;
        }

        // 获取Session对象
        HttpSession session = request.getSession();

        // 检查是否超过2分钟
        Long loginStartTime = (Long) session.getAttribute("loginStartTime");
        if (loginStartTime == null) {
            // 第一次访问，记录登录开始时间
            loginStartTime = System.currentTimeMillis();
            session.setAttribute("loginStartTime", loginStartTime);
        } else {
            if (currentTime - loginStartTime > 2 * 60 * 1000) {
                // 超过2分钟，重定向到 outtime.jsp
                response.sendRedirect("outtime.jsp");
                return;
            }
        }

        // 检查是否已经成功签到
        Boolean hasSignedIn = (Boolean) session.getAttribute("hasSignedIn");
        if (hasSignedIn != null && hasSignedIn) {
            // 已经签到过，重定向到 yes.jsp
            response.sendRedirect("yes.jsp");
            return;
        }

        // 获取用户提交的姓名和学号
        String name = request.getParameter("name");
        String studentId = request.getParameter("studentId");

        // 获取错误次数
        Integer errorCount = (Integer) session.getAttribute("errorCount");
        if (errorCount == null) {
            errorCount = 0;
        }

        PrintWriter out = response.getWriter();

        if (name == null || studentId == null) {
            // 名字或学号为空
            out.println("<script>alert('请输入姓名和学号');window.location.href='login.jsp';</script>");
            return;
        }

        name = name.trim();
        studentId = studentId.trim();

        if (studentMap.containsKey(name)) {
            String correctId = studentMap.get(name);
            if (correctId.equals(studentId)) {
                // 登录成功
                session.setAttribute("hasSignedIn", true);

                // 将学生姓名和学号写入 success.txt
                String filePath = getServletContext().getRealPath("/success.txt");
                try (PrintWriter writer = new PrintWriter(new java.io.FileWriter(filePath, true))) {
                    writer.println(name + "," + studentId);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 重定向到 yes.jsp，并传递姓名
                session.setAttribute("name", name);
                response.sendRedirect("yes.jsp");
                return;
            } else {
                // 学号错误
                errorCount++;
                session.setAttribute("errorCount", errorCount);
                String message = getErrorMessage(errorCount);
                out.println("<script>alert('" + message + "');window.location.href='login.jsp';</script>");
                return;
            }
        } else {
            // 姓名不存在
            errorCount++;
            session.setAttribute("errorCount", errorCount);
            String message = getErrorMessage(errorCount);
            out.println("<script>alert('" + message + "');window.location.href='login.jsp';</script>");
            return;
        }
    }

    // 根据错误次数返回不同的提示信息
    private String getErrorMessage(int errorCount) {
        switch (errorCount) {
            case 1:
                return "输错了哦";
            case 2:
                return "你干嘛~";
            default:
                return "别乱按";
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理 GET 请求
        doPost(request, response);
    }
}
